package com.jrx.anytxn.transaction.job.paph.config;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.SftpUtils;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.config.PaphFileConfig;
import com.jrx.anytxn.transaction.config.PaphSftpConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;

/**
 * @author liuyu
 * @Description 上传合并文件及md5文件
 */
@Configuration
@EnableConfigurationProperties(PaphFileConfig.class)
public class UploadBankFileConfiguration {
	private static final Logger logger = LoggerFactory.getLogger(UploadBankFileConfiguration.class);
	@Autowired
	public JobBuilderFactory jobBuilderFactory;
	@Autowired
	public StepBuilderFactory stepBuilderFactory;
	@Autowired
	private PaphSftpConfig paphSftpConfig;
	@Autowired
	private PaphFileConfig paphFileConfig;
	@Autowired
	private IOrganizationTableService organizationTableService;

	@Bean
	public Job uploadBankFileJob() {
		return jobBuilderFactory.get("uploadBankFileJob")
				.start(uploadBankFileStep1())
				.build();
	}

	@Bean
	public Step uploadBankFileStep1() {
		return stepBuilderFactory.get("uploadBankFileStep1")
				.tasklet(uploadBankFileTasklet1())
				.build();
	}

	@Bean
	@StepScope
	public Tasklet uploadBankFileTasklet1() {
		return (stepContribution, chunkContext) -> {
			logger.info("分库合并文件及相应md5文件上传开始。。。");
			// 获取连接
			SftpUtils.sftpConnect(paphSftpConfig.getUsername(), paphSftpConfig.getPassword(),
					paphSftpConfig.getHost(), paphSftpConfig.getPort());

			// 放款转账文件
			uploadFile(paphFileConfig.getTraAcctDetailFilePath(), TransBizConstant.TRA_ACCT_DETAIL,
					Constant.PRODECUT_TYPE_JY);
			uploadFile(paphFileConfig.getTraAcctDetailFilePath(), TransBizConstant.TRA_ACCT_DETAIL,
					Constant.PRODECUT_TYPE_XF);

			// 还款计划文件
			uploadFile(paphFileConfig.getPlanFilePath(), TransBizConstant.PLAN_FILE_NAME,
					Constant.PRODECUT_TYPE_JY);
			uploadFile(paphFileConfig.getPlanFilePath(), TransBizConstant.PLAN_FILE_NAME,
					Constant.PRODECUT_TYPE_XF);

			// 扣款结果文件
			uploadFile(paphFileConfig.getRepayDetailFilePath(), TransBizConstant.PREPAY_DETAIL,
					Constant.PRODECUT_TYPE_JY);
			uploadFile(paphFileConfig.getRepayDetailFilePath(), TransBizConstant.PREPAY_DETAIL,
					Constant.PRODECUT_TYPE_XF);

			// 关闭连接
			SftpUtils.disSftpConnect();
			logger.info("文件上传完毕。。");
			return RepeatStatus.FINISHED;
		};
	}

	private void uploadFile(String filePath, String fileType, String productType) throws Exception {
		// 业务日期
		PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
		String nextProcessDate = DateFormatUtils.format(org.getNextProcessingDate(), DateUtils.DATE_PATTERN_ANOTHER);
		String basePath =
				org.getTenantId() + File.separator + nextProcessDate + File.separator + productType + File.separator;

		// 获取文件
		String dateFileName =
				Constant.LS_BANK + productType + nextProcessDate + fileType + ".txt";
		String dateFilePath = filePath + basePath;
		File dateFile = new File(dateFilePath + dateFileName);
		String md5FileName =
				Constant.LS_BANK + productType + nextProcessDate + fileType + ".md5";
		File md5File = new File(dateFilePath + md5FileName);
		if (dateFile.exists() && md5File.exists()) {
			// 检查创建目录
			SftpUtils.createDir(paphSftpConfig.getUploadPath());
			// 上传文件
			SftpUtils.sftpUpload(dateFile);
			SftpUtils.sftpUpload(md5File);
		} else {
			logger.info("》》》》平安普惠文件上传《《《《{}_txt文件或md5文件不存在！", productType);
		}
	}
}